package com.cah.project.module.generate.controller;

import cn.hutool.core.date.DateUtil;
import com.cah.project.core.domain.out.CommonPageResult;
import com.cah.project.core.domain.out.CommonResult;
import com.cah.project.core.domain.out.PageList;
import com.cah.project.core.util.ModelViewUtil;
import com.cah.project.module.constant.ViewConstant;
import com.cah.project.module.generate.domain.vo.GenTableColumnInfo;
import com.cah.project.module.generate.domain.vo.GenTableInfo;
import com.cah.project.module.generate.domain.vo.in.GenTableQuery;
import com.cah.project.module.generate.domain.vo.out.DbTableList;
import com.cah.project.module.generate.domain.vo.out.GenTableList;
import com.cah.project.module.generate.service.IGenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器 控制层 <br/>
 */
@RestController
@RequestMapping("/gen")
@Api(tags = {"代码生成器"})
@RequiredArgsConstructor(onConstructor_ ={@Autowired, @Lazy})
public class GenController {

    private final IGenService genService;

    @GetMapping("main")
    public ModelAndView main() {
        return ModelViewUtil.stringView(ViewConstant.PATH_GEN_MAIN);
    }

    @GetMapping("view")
    public ModelAndView view(Model model, String id) {
        GenTableInfo info = genService.getGenTableById(id);
        return ModelViewUtil.dataView(ViewConstant.PATH_GEN_VIEW, model, info);
    }

    @GetMapping("importTable")
    public ModelAndView importTable() {
        return ModelViewUtil.stringView(ViewConstant.PATH_GEN_IMPORT_TABLE);
    }

    @GetMapping("column/list")
    @ApiOperation(value="查询表字段列表")
    public CommonResult<List<GenTableColumnInfo>> columnList(String tableId) {
        return CommonResult.data(genService.selectGenTableColumnInfoByTableId(Long.valueOf(tableId)));
    }

    @GetMapping("pageList")
    @ApiOperation(value="分页查询列表")
    public CommonPageResult<GenTableList> pageList(GenTableQuery query){
        PageList<GenTableList> pageList = genService.pageList(query);
        return CommonPageResult.data(pageList);
    }

    @GetMapping("db/pageList")
    @ApiOperation(value="分页查询数据当前数据库表列表")
    public CommonPageResult<DbTableList> dbPageList(GenTableQuery query){
        PageList<DbTableList> pageList = genService.dbPageList(query);
        return CommonPageResult.data(pageList);
    }

    @PostMapping("save")
    @ApiOperation(value="保存数据")
    public CommonResult<String> save(GenTableInfo info){
        genService.saveInfo(info);
        return CommonResult.ok();
    }

    @PostMapping("saveImport")
    @ApiOperation(value="保存引入数据")
    public CommonResult<String> saveImport(String tableNames){
        genService.saveImport(tableNames);
        return CommonResult.ok();
    }

    @PostMapping("remove")
    @ApiOperation(value="删除数据")
    public CommonResult<String> remove(String ids){
        genService.deleteByIds(ids);
        return CommonResult.ok();
    }

    @GetMapping("/preview/{id}")
    @ApiOperation(value="预览代码")
    public CommonResult<Map<String, String>> preview(@PathVariable("id") String tableId) {
        Map<String, String> dataMap = genService.previewCode(Long.valueOf(tableId));
        return CommonResult.data(dataMap);
    }

    @GetMapping("/genCode/{id}")
    @ApiOperation(value="生成代码（自定义路径）")
    @ResponseBody
    public CommonResult<String> genCode(@PathVariable("id") String tableId) {
        genService.genCode(Long.valueOf(tableId));
        return CommonResult.ok();
    }

    @GetMapping("/download/{id}")
    @ApiOperation(value="生成代码（下载方式）")
    public void download(HttpServletResponse response, @PathVariable("id") String tableId) throws IOException {
        byte[] data = genService.downloadCode(tableId);
        writeGenCode(response, data);
    }

    /**
     * 功能描述: 输出生成的代码文件 <br/>
     *
     * @param response response
     * @param data 字节数据
     */
    private void writeGenCode(HttpServletResponse response, byte[] data) throws IOException {
        if (data != null) {
            String fileName = "generate_" + DateUtil.currentSeconds() + ".zip";
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\" " + fileName + "\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.getOutputStream().write(data);
        }
    }

}
